/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package knowledgebase.service;

import java.util.List;
import knowledgebase.dao.RoleDAO;
import knowledgebase.model.Role;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 * @author eugene
 */
@Service("roleService")
public class RoleServiceImpl implements RoleService {

    Log log = LogFactory.getLog(getClass());
    @Autowired
    public RoleDAO dao;

    public void setDao(RoleDAO dao) {
        this.dao = dao;
    }
    
    @Override
    public List<Role> getAllRoles() {
        return dao.getAllRoles();
    }

    @Override
    public void saveOrUpdateRole(Role role) throws Exception {
        if(role.getName().length() > 5 && role.getName().substring(0, 5).toUpperCase().equals("ROLE_")) {
            role.setName(role.getName().toUpperCase());
        } else {
            role.setName("ROLE_" + role.getName().toUpperCase());
        }
        try {
            dao.addOrUpdateRole(role);
        } catch (Exception ex) {
            String message = "";
            Throwable throwable = ex;
            do {
                if (throwable.getMessage().indexOf("UK_ROLE_NAME") != -1) {
                    message = "Role with the same name already exists";
                    log.error(message + "\n" + ex);
                }
            } while ((throwable = throwable.getCause()) != null);
            throw new Exception(message, ex);
        }
    }

    @Override
    public void removeRole(long roleId) {
        dao.removeRole(roleId);
    }
    
    @Override
    public Role getRoleByName(String roleName) {
        if(roleName.length() > 5 && roleName.substring(0, 5).toUpperCase().equals("ROLE_")) {
            roleName = roleName.toUpperCase();
        } else {
            roleName = "ROLE_" + roleName.toUpperCase();
        }
        return dao.getRoleByName(roleName);
    }
    
    @Override
    public List<Role> searchRoles(String name, int startIndex, int size){
        return dao.searchRoles(name, startIndex, size);
    }
    
    @Override
    public long getUserCount() {
        return dao.getUserCount();
    }
}